package com.yazi.mxz.admin.controller;


import javax.annotation.Resource;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.tool.PageLink;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.jackson.result.ListResult;
import com.myframework.smhj.jackson.result.StatusResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yazi.mxz.admin.jackson.filter.RoleFilter;
import com.yazi.mxz.common.controller.BaseController;
import com.yazi.mxz.common.entity.beans.Role;
import com.yazi.mxz.common.service.RoleService;

@Controller("roleController")
@RequestMapping("/role")
public class RoleController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(RoleController.class);
	
	@Resource
	RoleService roleService;
	
	@RequestMapping("/list")
	public String list(Role role, Searching si, Model model){
		log.debug("进入角色列表页面");
		Page<Role> page = roleService.list(role, si);
		PageLink pageLink = new MyPageLink(page.getPaging());
		model.addAttribute("roleList", page.getList());
		model.addAttribute("pageLink", pageLink);
		model.addAttribute("searchWord", si.getSearchWord());
		return "role_list";
	}
	
	@RequestMapping("/list/json")
	@ResponseBody
	public ListResult<?> listJson(Role role, Searching si){
		log.debug("获取角色列表数据");
		ListResult<Role> jsonResult = new ListResult<Role>();
		jsonResult.setFilter(RoleFilter.get());
		try {
			Page<Role> page = roleService.list(role, si);
			jsonResult.setResult(page.getList());
			jsonResult.setOk();
		} catch(Exception e) {
			log.debug("获取角色列表数据异常:", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}
	
	@RequestMapping("/addOrEdit")
	public String addOrEdit(Role role, Model model) {
		Long roleId = role.getRoleId();
		if (null != roleId) {
			log.debug("进入角色编辑页面：role={}", role);
			role = roleService.one(roleId);
		} else {
			log.debug("管理->进入角色添加页面");
		}
		model.addAttribute("role", role);
		return "role_addOrEdit";
	}
	
	@RequestMapping("/addOrEditDo/json")
	@ResponseBody
	public StatusResult addOrEditDoJson(Role role) {
		log.debug("添加/编辑角色：roleId={}", role.getRoleId());
		StatusResult jsonResult = new StatusResult();
		try {
			roleService.addOrEdit(role);
			jsonResult.setOkMessage("提交成功");
		} catch (MyException e) {
			log.debug("添加/编辑角色失败: {}", e.getMessage());
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			log.debug("添加/编辑角色异常:", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}
}
